package com.sky.common.task;

import com.sky.business.sys.domain.CameraConfig;
import com.sky.business.sys.dto.OnvifDeviceInfo;
import com.sky.business.sys.service.CameraConfigService;
import com.sky.business.sys.service.OnvifService;
import com.sky.common.utils.NumberUtil;
import com.sky.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 获取设备的厂商、型号、防火墙版本和序列号持久化到数据库
 *
 */
@Slf4j
@Component
public class OnvifDeviceInfoQueryTask {

    @Autowired
    private CameraConfigService cameraConfigService;

    @Autowired
    private OnvifService onvifService;

    @Scheduled(cron = "0 30 * * * ?")
    public void doTask() {
        List<CameraConfig> cameraConfigList = cameraConfigService.list();
        for (CameraConfig cameraConfig : cameraConfigList) {
            if (StringUtils.isNotEmpty(cameraConfig.getManufacturer()) && StringUtils.isNotEmpty(cameraConfig.getModel()) && StringUtils.isNotEmpty(cameraConfig.getFirmwareVersion()) && StringUtils.isNotEmpty(cameraConfig.getSerialNumber())) {
                continue;
            }
            try {
                OnvifDeviceInfo onvifDeviceInfo = onvifService.getDeviceInformation(cameraConfig.getCameraIp(), NumberUtil.parseInt(cameraConfig.getCameraPort()), cameraConfig.getOnvifUser(), cameraConfig.getOnvifPasswd());
                cameraConfigService.updateOnvifDeviceInfo(cameraConfig.getId(), onvifDeviceInfo.getManufacturer(), onvifDeviceInfo.getModel(), onvifDeviceInfo.getFirmwareVersion(), onvifDeviceInfo.getSerialNumber());
            } catch (Exception e) {
                log.info("获取设备制造商、型号等数据时发生异常,设备ID:{}", cameraConfig.getCameraDeviceId(), e);
            }
        }
    }
}
